/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package SnpDbHandling;

import java.awt.BorderLayout;
import java.awt.Color;
import java.io.IOException;
import java.rmi.RMISecurityManager;
import java.rmi.activation.ActivationException;
import java.rmi.registry.LocateRegistry;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.SimpleFormatter;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

/**
 * Class which acts as entry point for SnippetBase server
 * @author Łukasz 'byku' Guzik
 */
class MainWindow extends JFrame
{
    JCheckBox autoScroll;
    JTextArea console;
    JScrollPane scrollPane;

    class ConHandler extends Handler
    {
	private MainWindow output;

	public ConHandler(MainWindow output)
	{
	    setFormatter(new SimpleFormatter());
	    setLevel(Level.ALL);
	    this.output = output;
	}

	@Override
	public void close() throws SecurityException
	{
	}

	@Override
	public void flush()
	{
	}

	@Override
	public void publish(LogRecord record)
	{
	    output.appendText(getFormatter().format(record)
		    + System.getProperty("line.separator"));
	}
    }

    public MainWindow()
    {
	this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	autoScroll = new JCheckBox("Autoscroll console", true);
	this.add(autoScroll, BorderLayout.SOUTH);

	console = new JTextArea();
	console.setAutoscrolls(true);
	console.setEditable(false);
	console.setForeground(Color.LIGHT_GRAY);
	console.setBackground(Color.BLACK);
	try
	{
	    DBHndLogger.getLOGGER().addHandler(new ConHandler(this));
	} catch(IOException e)
	{
	    DBHndLogger.logException(Level.WARNING, e);
	}

	scrollPane = new JScrollPane(console);
	scrollPane.setAutoscrolls(true);
	this.add(scrollPane);
    }

    public void appendText(String text)
    {
	console.append(text);

	if(autoScroll.isSelected())
	{
	    console.setCaretPosition(console.getText().length());
	}
    }
}

public class Main
{
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException,
	    ActivationException
    {
	MainWindow window = new MainWindow();
	window.setSize(600, 400);
	window.setTitle("SnippetManager Server");
	window.setVisible(true);

	DBHndLogger.logMessage(Level.FINEST, "Setting new security manager");
	System.setSecurityManager(new RMISecurityManager());

	try
	{
	    LocateRegistry.createRegistry(2001);
	    String name = "rmi://localhost:2001/snpdbhandling";
	    DBConnector conObj = new DBConnector();
	    java.rmi.Naming.rebind(name, conObj);
	    DBHndLogger.logMessage(Level.FINER, "Interfejs zbindowany");
	    DBHndLogger.logMessage(Level.FINER, "Server uruchomiony!");
	} catch(Exception e)
	{
	    DBHndLogger.logException(Level.SEVERE, e);
	    window.appendText("Serwer nie funkcjonuje!");
	}
    }
}
